﻿
using Masuit.Tools.Database;
using Microsoft.EntityFrameworkCore;
using Models.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilsBase;
using UtilsCache;
using UtilsORM;
using UtilsORM.MySqlData;

namespace ServiceWeb.DBGateway
{
    public class DBIotDeviceLinkage
    {
        EFYihongIotContext ef = new EFYihongIotContext();

        public List<iot_device_linkage> getLinkageList(string cguid, int status)
        {
            return ef.iot_device_linkage.Where(c => c.l_c_guid == cguid && c.l_status == status).ToList();

        }
        public iot_device_linkage getLinkage(string guid)
        {
            return ef.iot_device_linkage.Where(c => c.l_guid == guid).FirstOrDefault();

        }

        /// <summary>
        /// 删除缓存，以便在ServiceCloudLinkageCondition中，更新操作
        /// </summary>
        public void delLinkageconditionRedisCache()
        {
            try
            {
                List<iot_device_linkage> linkages = ef.iot_device_linkage.ToList();
                foreach (iot_device_linkage item in linkages)
                {
                    UtilMemoryCacheHelper.remove("iot_device_linkage_condition" + item.l_guid);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 删除缓存，以便在ServiceCloudLinkageCondition中，更新操作,异步
        /// </summary>
        public async void delLinkageRedisCache()
        {
            await Task.Run(() =>
             {
                 try
                 {

                     List<string> deviceGuids = ef.iot_device_linkage_condition.Where(c => c.lc_operation == "main").Select(c => c.lc_d_guid).Distinct().ToList();
                     foreach (string guid in deviceGuids)
                     {
                         UtilMemoryCacheHelper.remove("iot_device_linkage" + guid);
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex);
                 }
             });
        }

        public bool saveAll(MagerLoginInfo LoginUserInfo, iot_device_linkage req)
        {
            //删除缓存，即时生效，否则一分钟后生效

            UtilMemoryCacheHelper.remove("iot_device_linkage_condition" + req.l_guid);

            //先查一下有没重复提交
            iot_device_linkage model = ef.iot_device_linkage.Where(c => c.l_guid == req.l_guid).FirstOrDefault();
            if (model == null)
            {

                iot_device_linkage linkagemodel_no = ef.iot_device_linkage.Where(c => c.l_p_guid == req.l_p_guid).OrderByDescending(c => c.l_p_model_no).FirstOrDefault();

                if (linkagemodel_no != null && linkagemodel_no.l_p_model_no != null)
                {
                    req.l_p_model_no = linkagemodel_no.l_p_model_no + 1;
                }
                else
                {
                    req.l_p_model_no = 1;
                }

                //写入
                req.l_c_guid = LoginUserInfo.userCompanyGuid;
                req.l_cu_guid = LoginUserInfo.user_guid;
                req.l_mod_time = req.l_add_time = DateTime.Now;
                req.l_auto_run = 0;//0启动，1不启动
                req.l_auto_run_join = 0;//0不参与自动配置，1参与自动配置
                if (!string.IsNullOrEmpty(req.l_p_guid))
                {
                    req.l_is_template = 2;
                    req.l_c_guid = ef.iot_product.Where(c => c.p_guid == req.l_p_guid).FirstOrDefault().p_c_guid;
                }
                ef.iot_device_linkage.Add(req);
                ef.SaveChanges();
            }
            else
            {

                model.l_title = req.l_title;
                model.l_status = req.l_status;
                model.l_condition_type = req.l_condition_type;
                model.l_mod_time = req.l_add_time = DateTime.Now;
                ef.iot_device_linkage.Update(model);
                ef.SaveChanges();
            }

            
                //开启预警
                //int count = ef.iot_device_linkage_warn.Where(c => c.w_l_guid == req.l_guid).ExecuteUpdate(c => c.SetProperty(p => p.w_status, warn));
                //if (count < 1)
                //{
                //    iot_device_linkage_warn linkage_Warn = new iot_device_linkage_warn();
                //    linkage_Warn.w_guid = Guid.NewGuid().ToString();
                //    linkage_Warn.w_l_guid = req.l_guid;
                //    linkage_Warn.w_status = warn;
                //    linkage_Warn.w_add_time = DateTime.Now;
                //    linkage_Warn.w_warn_status = 0;
                //    ef.iot_device_linkage_warn.Add(linkage_Warn);
                //    ef.SaveChanges();
                //}
            
            return true;
        }
        public bool changeStatus(string l_guid)
        {
            iot_device_linkage model = ef.iot_device_linkage.Where(c => c.l_guid == l_guid).FirstOrDefault();
            if (model != null)
            {
                if (model.l_status == 0)
                {
                    model.l_status = 1;
                }
                else
                {
                    model.l_status = 0;
                }
                ef.SaveChanges();
            }
            delLinkageRedisCache();
            return true;
        }

        public bool changeStatus(string pguid, int modelno, int status)
        {
            iot_device_linkage model = ef.iot_device_linkage.Where(c => c.l_p_guid == pguid && c.l_p_model_no == modelno).FirstOrDefault();
            if (model != null)
            {
                model.l_status = status;
                ef.SaveChanges();
            }
            delLinkageRedisCache();
            return true;
        }

        public List<iot_device_linkage> getLinkageLists(string pguid)
        {
            return ef.iot_device_linkage.Where(c => c.l_p_guid == pguid).ToList();

        }

        public DataTable getLinkageLists_dt(string pguid, string modelno)
        {
            var list = ef.iot_device_linkage.Where(c => c.l_p_guid == pguid);

            if (!string.IsNullOrEmpty(modelno))
            {
                string[] nos = modelno.Split(',');
                List<int> arrs = new List<int>();   //用来存放将字符串转换成int[]
                for (int i = 0; i < nos.Length; i++)
                {
                    if (!string.IsNullOrEmpty(nos[i]))
                    {
                        arrs.Add(int.Parse(nos[i]));
                    }
                }
                if (arrs.Count > 0)
                {
                    list = list.Where(c => arrs.Contains((int)c.l_p_model_no));
                }
            }
            var result = list.Select(c => new { c.l_status, c.l_p_model_no });
            return result.ToDataTable();
        }
    }
}
